<template>
  <div class="incoming-list">
    <el-form :inline="true" class="search-form" label-width="80px">

      <el-form-item label="文件标题">
        <el-input v-model="query.title" placeholder="请输入文件标题" style="width: 200px"></el-input>
      </el-form-item>

      <el-form-item label="发文/收文单位">
        <el-input v-model="query.senderOrg" placeholder="请输入发文单位" style="width: 200px"></el-input>
      </el-form-item>

      <el-form-item label="密级">
        <el-select v-model="query.secretLevel" placeholder="请选择密级" style="width: 180px">
          <el-option label="普通" value="普通"></el-option>
          <el-option label="秘密" value="秘密"></el-option>
          <el-option label="机密" value="机密"></el-option>
          <el-option label="绝密" value="绝密"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="密件类型">
        <el-select v-model="query.secretType" placeholder="请选择密件类型" style="width: 180px">
          <el-option label="普通件" value="0"></el-option>
          <el-option label="密件" value="1"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="info" plain @click="loadData(1)">查询</el-button>
        <el-button type="warning" plain style="margin-left: 10px" @click="resetQuery">重置</el-button>
      </el-form-item>

      <div class="toolbar" style="margin: 20px 0">
        <el-button type="success" @click="handleArchive">批量存档</el-button>
      </div>

      <el-table
          :data="tableData"
          stripe
          border
          @selection-change="handleSelectionChange"
          style="width: 100%; margin-top: 20px"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="senderDocNo" label="发文/收文编号" width="200">
          <template v-slot="scope">
             <span :style="isToday(scope.row.limitDate) ? { color: 'red' } : {}">
              {{ scope.row.senderDocNo }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="title" label="文件标题" width="220">
          <template v-slot="scope">
             <span :style="isToday(scope.row.limitDate) ? { color: 'red' } : {}">
              {{ scope.row.title }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="senderOrg" label="发文单位" width="180">
          <template v-slot="scope">
             <span :style="isToday(scope.row.limitDate) ? { color: 'red' } : {}">
              {{ scope.row.senderOrg }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="secretLevel" label="密级" width="100">
          <template v-slot="scope">
             <span :style="isToday(scope.row.limitDate) ? { color: 'red' } : {}">
              {{ scope.row.secretLevel }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="archiveDate" label="存档日期" width="120">
          <template v-slot="scope">
             <span :style="isToday(scope.row.limitDate) ? { color: 'red' } : {}">
              {{ scope.row.archiveDate }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="handlingOrg" label="办件单位" width="180">
          <template v-slot="scope">
             <span :style="isToday(scope.row.limitDate) ? { color: 'red' } : {}">
              {{ scope.row.handlingOrg }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="limitDate" label="限办日期" width="120">
          <template v-slot="scope">
             <span :style="isToday(scope.row.limitDate) ? { color: 'red' } : {}">
              {{ scope.row.limitDate }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="processStatus" label="处理状态" width="80">
          <template v-slot="scope">
             <span :style="isToday(scope.row.limitDate) ? { color: 'red' } : {}">
              {{ scope.row.processStatus }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="objectName" label="当前审批人" width="180">
          <template v-slot="scope">
             <span :style="isToday(scope.row.limitDate) ? { color: 'red' } : {}">
              {{ scope.row.nextObjectName || scope.row.objectName || '未分配' }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="240">
          <template v-slot="scope">
            <el-button size="mini" @click="handleDetail(scope.row)">详情</el-button>
            <el-button size="mini" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
          :current-page="pageNum"
          :page-sizes="[10, 20, 50]"
          :page-size="pageSize"
          layout="total, prev, pager, next"
          :total="total"
          @current-change="handlePageChange"
          style="margin-top: 30px"
      ></el-pagination>
    </el-form>
  </div>
</template>
<script>
export default {
  name: "restrictedDocuments",
  data() {
    return {
      tableData: [],
      query: {
        title: "",
        senderOrg: "",
        secretLevel: "",
        secretType: null, // 0-普通件，1-密件
      },
      pageNum: 1,
      pageSize: 10,
      total: 0,
      selectedIds: [],
      selectedRows: []
    };
  },
  created() {
    this.loadData(1);
  },
  methods: {
    loadData(pageNum) {
      if (pageNum) this.pageNum = pageNum;
      this.$request.get('/restricted-documents/selectPage', {
        params: {
          pageNum: this.pageNum,
          pageSize: this.pageSize,
          // 展开查询条件（与后端IncomingDoc实体字段一一对应）
          ...this.query
        }
      }).then(res => {
        console.log(res)
        let dataList = res.data.list;
        console.log("dataList", dataList)
        dataList.forEach(item => {
          item.objectName = item.objectName ? item.objectName : "办公室";
        })
        this.tableData = dataList;    // 表格数据
        this.total = res.data.total;
      })
    },
    resetQuery() {
      this.query = {
        title: '',
        senderOrg: '',
        secretLevel: '',
        secretType: null // 密件类型（0-普通件，1-密件）
      };
      this.loadData(1);  // 重置后重新加载第一页
    },
    handleSelectionChange(rows) {
      this.selectedIds = rows.map(row => row.id);
      this.selectedRows = rows;
    },
    // 分页页码变化
    handlePageChange(pageNum) {
      this.loadData(pageNum);
    },
    handleDetail(row) {
      console.log(row);
      const {sourceType, id} = row;
      // 根据来源类型确定路由前缀
      const prefix = sourceType === "OUTGOING" ? "outgoing-doc" : "incoming-doc";
      // 跳转到对应的详情页面
      this.$router.push(`/${prefix}-detail/${id}`);
    },
    handleEdit(row) {
      const {sourceType, id, secretType} = row;
      // 根据来源类型确定路由前缀（转为小写并添加连字符，符合路由命名规范）
      const prefix = sourceType === "OUTGOING" ? "outgoing-doc" : "incoming-doc";
      // 跳转到对应的编辑页面
      this.$router.push(`/${prefix}-edit/${id}`);
    },
    handleDelete(row) {
      const {sourceType, id} = row;
      const isOutgoing = sourceType === "OUTGOING";
      const confirmMsg = isOutgoing ? '确定删除该发文？' : '确定删除该收文？';

      this.$confirm(confirmMsg, '提示', {type: 'warning'})
          .then(() => {
            // 显示加载状态（如果有全局加载组件）
            this.loading = true;

            const url = isOutgoing
                ? `/outgoingDoc/delete/${id}`
                : `/incomingDoc/delete/${id}`;

            return this.$request.delete(url);
          })
          .then(res => {
            if (res.code === '200') {
              this.$message.success(`${isOutgoing ? '发文' : '收文'}删除成功`);
              this.loadData(this.pageNum); // 刷新当前页
            } else {
              this.$message.error(res.msg || '删除失败，请重试');
            }
          })
          .catch(error => {
            // 取消确认时也会进入catch，需要区分处理
            if (error !== 'cancel') {
              this.$message.error('操作失败：' + (error.message || '网络错误'));
            }
          })
          .finally(() => {
            // 无论成功失败，都关闭加载状态
            this.loading = false;
          });
    },
    handleArchive() {
      const { selectedRows } = this;
      if (selectedRows.length === 0) {
        this.$message.warning('请选择需要存档的数据');
        return;
      }

      // 1. 分离两种类型的ID（收文INCOMING、发文OUTGOING）
      const incomingIds = []; // 收文ID列表
      const outgoingIds = []; // 发文ID列表
      selectedRows.forEach(row => {
        if (row.sourceType === 'INCOMING') {
          incomingIds.push(row.id);
        } else if (row.sourceType === 'OUTGOING') {
          outgoingIds.push(row.id);
        }
      });

      // 2. 生成确认信息（根据选中的类型）
      let confirmMsg = '';
      if (incomingIds.length > 0 && outgoingIds.length > 0) {
        confirmMsg = '确定批量存档选中的收文和发文？';
      } else if (incomingIds.length > 0) {
        confirmMsg = '确定批量存档选中的收文？';
      } else {
        confirmMsg = '确定批量存档选中的发文？';
      }

      // 3. 弹出一次确认框
      this.$confirm(confirmMsg, '提示', { type: 'warning' })
          .then(() => {
            // 4. 准备请求：按类型调用对应接口
            const requests = [];
            // 收文请求
            if (incomingIds.length > 0) {
              incomingIds.forEach(id => {
                requests.push(this.$request.put(`/incomingDoc/archive/${id}`));
              });
            }
            // 发文请求
            if (outgoingIds.length > 0) {
              outgoingIds.forEach(id => {
                requests.push(this.$request.put(`/outgoingDoc/archive/${id}`));
              });
            }

            // 5. 批量执行请求
            return Promise.all(requests);
          })
          .then(() => {
            // 6. 全部成功
            this.$message.success('批量存档成功');
            this.loadData(this.pageNum); // 刷新当前页
          })
          .catch(error => {
            // 7. 处理失败（包括用户取消和请求错误）
            if (error !== 'cancel') { // 排除用户主动取消的情况
              this.$message.error('批量存档失败：' + (error.message || '网络错误'));
            }
          });
    },
    isToday(dateString) {
      console.log(dateString)
      if (!dateString) return false;

      const datePart = dateString.split(' ')[0];

      const today = new Date();
      const todayStr = today.getFullYear() + '-' + String(today.getMonth() + 1).padStart(2, '0') + '-' + String(today.getDate()).padStart(2, '0');
      console.log(todayStr)

      return datePart === todayStr;
    }
  }
}

</script>
<style>

</style>
